import { useState, useEffect } from 'react';

// 简单的全局计时器 - 避免复杂的EventEmitter
class SimpleGlobalTimer {
  constructor() {
    this.time = 45;
    this.isRunning = false;
    this.timer = null;
    this.subscribers = new Set();
  }

  // 订阅状态变化
  subscribe(callback) {
    this.subscribers.add(callback);
    
    // 立即通知当前状态
    callback({ time: this.time, isRunning: this.isRunning });
    
    // 返回取消订阅函数
    return () => {
      this.subscribers.delete(callback);
    };
  }

  // 通知所有订阅者
  notify() {
    const state = { time: this.time, isRunning: this.isRunning };
    this.subscribers.forEach(callback => {
      try {
        callback(state);
      } catch (error) {
        console.error('Timer subscriber error:', error);
      }
    });
  }

  // 开始计时
  start() {
    if (this.isRunning) return; // 防止重复启动
    
    this.isRunning = true;
    this.notify();
    
    this.timer = setInterval(() => {
      this.time -= 1;
      this.notify();
      
      if (this.time <= 0) {
        this.stop(); // 到0时停止，不自动重置
      }
    }, 1000);
  }

  // 重置计时器
  reset(newTime = 45) {
    this.stop();
    this.time = newTime;
    this.start();
  }

  // 停止计时器
  stop() {
    if (this.timer) {
      clearInterval(this.timer);
      this.timer = null;
    }
    this.isRunning = false;
    this.notify();
  }

  // 获取当前状态
  getState() {
    return { time: this.time, isRunning: this.isRunning };
  }

  // 销毁计时器，重置为45秒但不开始倒计时
  destroy() {
    this.stop();                // 停止计时器
    this.time = 45;             // 重置时间为45秒
    this.notify();              // 通知所有订阅者时间已重置为45
    this.subscribers.clear();    // 清除所有订阅者
    console.log('Timer destroyed, reset to 45s, all subscribers cleared');
  }
}

// 创建全局实例
export const globalTimer = new SimpleGlobalTimer();

// Hook
export const useGlobalTimer = () => {
  const [timerState, setTimerState] = useState(() => globalTimer.getState());

  useEffect(() => {
    const unsubscribe = globalTimer.subscribe(setTimerState);
    return unsubscribe;
  }, []);

  return {
    ...timerState,
    refresh: () => globalTimer.reset(45),
    start: () => globalTimer.start(),
    stop: () => globalTimer.stop(),
    destroy: () => globalTimer.destroy()
  };
};
